<?php
/**
 * PHP Daycare
 * function.php
 * @author Jason Butz
 * @version 0.0
 * @package PHPDaycare
 */
/**
 * Include config.php so that we can use the database.
 * Using include_once to be sure that we don't get multiple copies when functions.php is included
 */
include_once('config.php');

/*****************************************
		Session things
*****************************************/
/**
 * session
 * Controls a user's session. As a reminder "session_start();" MUST be called in all files using sessions!
 * @package PHPDaycare
 */
class session
{
	/**
	 * session_setup
	 * Sets up the session with the username and a doubly encrypted password as the session variables
	 * @param string $user the username of the user who we are setting the session up for
	 * @param string $pass the user's password as it is in the database
	 * @return boolean
	 */
	function session_setup($user, $pass)
	{
		// Our session is going to consist of the username
		//		and the SHA1 + md5 of the password.
	
		// First be sure a session is not set
		if(!isset($_SESSION['pass']))
		{
			$_SESSION['user'] = $user;
			$_SESSION['pass'] = sha1(md5($pass));
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
	/**
	 * session_delete
	 * Delete any current session
	 */
	function session_delete()
	{
		unset($_SESSION['user']);
		unset($_SESSION['pass']);
	}
	/**
	 * isloggedin
	 * Checks to see if the current session is a valid one if no session exists then FALSE is returned.
	 * @return boolean
	 */
	function isloggedin()
	{
		if(isset($_SESSION['user']))
		{
			$r = $GLOBALS['db']->query("SELECT ID FROM worker WHERE username='" . $_SESSION['user'] . "';");
			if($row = mysql_fetch_array($r))
			{
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		}
		else
		{
			return FALSE;
		}
	}
}
$session = new session();
/**
 * Deals with event logging
 *	@package PHPDaycare
 */
class eventlogger
{
	/**
	 * login
	 * Logs a worker's login
	 * @param string $name Worker's name
	 * @access public
	 */
	public function login($name)
	{
		$oname = "Worker Login - $name";
		$desc = "$name logged into the system.";
		$this->logIT($oname, $desc);
	}
	/**
	 * logout
	 * Logs a worker logging out
	 * @param string $name Worker's name
	 * @access public
	 */
	public function logout($name)
	{
		$oname = "Worker Logout - $name";
		$desc = $name . ' logged out of the system.';
		$this->logIT($oname, $desc);
	}
	/**
	 * adminLogin
	 * Logs administrator panel access
	 * @param string $name Administrator's name
	 * @access public
	 */
	public function adminLogin($name)
	{
		$oname = "Administrator Panel Login - $name";
		$desc = $name . ' logged into the administrator panel';
		$this->logIT($oname, $desc);
	}
	/**
	 * adminLogout 
	 * Logs administrator panel logout
	 * @param string $name Administrator's name
	 * @access public
	 */
	public function adminLogout($name)
	{
		$oname = "Administrator Panel Logout - $name";
		$desc = $name . ' logged out of the administrator panel';
		$this->logIT($oname, $desc);
	}
	/**
	 * loginFailW
	 * Logs a failed worker login
	 * @param string $uname username used for failed login
	 * @access public
	 */
	public function loginFailW($uname)
	{
		$name = 'Failed Worker Login';
		$desc = 'A failed login attempt occured at the worker login screen. The username used was "'.$uname.'".';
		$this->logIT($name, $desc);
	}
	/**
	 * loginFailA
	 * Logs a failed administrator login
	 * @param string $uname username used for failed login
	 * @access public
	 */
	public function loginFailA($uname)
	{
		$name = 'Failed Administator Login';
		$desc = "A failed login attempt occured at the administraor login screen. The username used was \"$uname\".";
		$this->logIT($name, $desc);
	}
	/**
	 * checkin
	 * Logs a child being checked in
	 * @param string $cname Child's id
	 * @param string $aname Adult's id
	 * @param string $wname Worker's name
	 * @access public
	 */
	public function checkin($cname, $aname, $wname)
	{
		$r = $GLOBALS['db']->query("SELECT name FROM child WHERE ID = $cname");
		$cname = mysql_result($r, 0);
		$r = $GLOBALS['db']->query("SELECT name FROM adults WHERE ID = $aname");
		$aname = mysql_result($r, 0);
		$name = "Child Checked In";
		$desc = "$cname was dropped off by $aname. $wname checked them in.";
		$this->logIT($name, $desc);
	}
	/**
	 * checkout
	 * Logs a child being picked up
	 * @param string $cname Child's id
	 * @param string $aname Adult's id
	 * @param string $wname Worker's name
	 * @access public
	 */
	public function checkout($cname, $aname, $wname)
	{
		$r = $GLOBALS['db']->query("SELECT name FROM child WHERE ID = $cname");
		$cname = mysql_result($r, 0);
		$r = $GLOBALS['db']->query("SELECT name FROM adults WHERE ID = $aname");
		$aname = mysql_result($r, 0);
		$name = "Child Checked Out";
		$desc = "$cname was picked up by $aname. $wname checked them out.";
		$this->logIT($name, $desc);
	}
	/**
	 * logIT
	 * Runs the SQL query to enter the event into the database
	 * @param string $name event name
	 * @param string $desc event describtion
	 * @access protected
	 */
	protected function logIT($name, $desc)
	{
		$GLOBALS['db']->query('INSERT INTO `event` (`ename`, `edesc`, `etime`) VALUES ("'.mysql_escape_string($name).'","'.mysql_escape_string($desc).'",NOW());');
	}
}
$log = new eventlogger();
/******************************************/
/*     File Uploading Code                */
/******************************************/
/**
 * FileUpload
 * Assists with the uploading of files. At this time it will only work on images (jpg, jpeg) due to that being the only forseeable need
 * @package PHPDaycare
 */
class FileUpload
{
	/**
	 * @var integer $MAX_SIZE Used as the maximum file size we will allow. For us it will be 5MB by default.  
	 */
	protected $MAX_SIZE = 5242880; // 5MB
	/**
	 * isImg 
	 * Used to check if a file seems to be a valid jpeg
	 * @param string $file The name of the file as used in the FORM
	 * @access public
	 * @return boolean
	 */
	public function isImg($file)
	{
		// First, do we have a file?
		if($file["size"] > 0)
		{
			// We have a file, but is it too big?
			if($file["size"] <= this.MAX_SIZE)
			{
				// Is it an image? (jpg, jpeg only);
				if($file["type"] == "image/jpeg" ||
					$file["type"] == "image/pjpeg") // The pjpeg is apparently for IE. Damn them being different!
				{
					// We have a valid image as far as we can tell!
					return TRUE;
				}
			}
		}
		// Guess it isn't valid
		return FALSE;
	}
	/**
	 * todisk 
	 * Moves a file from the temporary directory to a destination
	 * @param string $file The name of the upload element from the form
	 * @param string $dir The path to save the file. Do not end it in /
	 * @access public
	 * @return mixed
	 */
	public function todisk($file, $dir)
	{
		// First we check if it is valid!
		if(this.isImg($file))
		{
			// It appears to be valid so lets move it from
			// the temporary location to the final one. I hope
			// they didn't mess up the $dir variable
			if (file_exists($dir . '/' . $file["name"]))
			{
				// File exists
				return FALSE;
			}
			else
			{
				$fname = $dir . '/' . $file['name'];
				if(move_uploaded_file($file['tmp_name'], $fname))
				{
					// We moved it!
					return $fname;
				}
				else
				{
					// We didn't move it :(
					return FALSE;
				}
			}
		}
		else
		{
			return FALSE;
		}
	}
	/**
	 * todatabase 
	 * Used to get the data for the blob, which is inserted in the database 
	 * @param string $img The name as used in the form
	 * @access public
	 * @return mixed Returns the data for the database or FALSE
	 * @link http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx
	 */
	public function todatabase($img)
	{
		if($this.isImg($img))
		{
			// We have a valid image as far as we know
			// Now to open it and read it in
			$fp      = fopen($img['tmp_name'], 'r');
			$content = fread($fp, filesize($img['tmp_name']));
			fclose($fp);
			return $content;
		}
		else
		{
			return FALSE;
		}
	}
}
$upload = new FileUpload();
/**************************************************************/
/*            Template things                                 */
/**************************************************************/
/**
 * Template 
 * This class is used to parse templates files in ./template and to output the HTML
 * @package PHPDaycare
 */
class Template
{
	/**
	 * fileExists 
	 * Used to see if we have a template file by the name given
	 * @param string $name
	 * @access protected
	 * @return boolean
	 */
	protected function fileExists($name)
	{
		$file = $config->$base_path . 'template/' . $name . '.tpl';
		if(file_exists($file) && is_readable($file))
			return TRUE;
		else
			return FALSE;
	}
	/**
	 * readTemplate 
	 * Reads a template file from the disk. No checks for the file are made
	 * @param string $name 
	 * @access protected
	 * @return string
	 */
	protected function readTemplate($name)
	{
		$handle = fopen($GLOBALS['config']->base_path . "template/$name.tpl", "r");
		$contents = fread($handle, filesize($GLOBALS['config']->base_path . "template/$name.tpl"));
		fclose($handle);
		return $contents;
	}
	/**
	 * getMain 
	 * Reads the main template file from the disk
	 * @access protected
	 * @return string
	 */
	protected function getMain()
	{
		if($this->fileExists("main"))
		{
			return $this->readTemplate("main");
		}
		else
		{
			die("Error: The template file 'main.tpl' does not exist.");
		}
	}
	/**
	 * getMenu 
	 * Reads the menu template file from the disk
	 * @access protected
	 * @return string
	 */
	protected function getMenu()
	{
		if($this->fileExists("menu"))
		{
			return $this->readTemplate("menu");
		}
		else
		{
			die("Error: The template file 'menu.tpl' does not exist.");
		}
	}
	/**
	 * parse 
	 * Parses the given $content for $match and replaces it with $replace
	 * @param string $match 
	 * @param string $replace 
	 * @param string $content 
	 * @access protected
	 * @return string
	 */
	protected function parse($match, $replace, $content)
	{
		return str_replace($match,$replace,$content);
	}
	/**
	 * display 
	 * Displays the main page using the template name given for the main content
	 * @param string $tmpl 
	 * @param boolean $menu OPTIONAL Default value is TRUE
	 * @access public
	 * @return void
	 */
	public function display($tmpl, $menu = TRUE)
	{
		if($this->fileExists($tmpl))
		{
			// Read the main template
			$page = $this->getMain();
			// Parse for menu if we need to
			if($menu)
			{
				$menutxt = $this->getMenu();
			}
			else
			{
				$menutxt = "";
			}
			$page = $this->parse("{{MENU}}", $menutxt, $page);
			// Parse for the main content
			$page = $this->parse("{{CONTENT}}", $this->readTemplate($tmpl), $page);
			// Parse for organization name
			$page = $this->parse("{{ORG}}", $GLOBALS['config']->org_name, $page);
			// Output the page
			echo $page;
		}
		else
		{
			die("Error: template '$tmpl.tpl' does not exist.");
		}
	}
	/**
	 * displayCont 
	 * Displays the main page and allows you to specify the content
	 * @param string $txt 
	 * @param boolean $menu OPTIONAL Default value is TRUE
	 * @access public
	 * @return void
	 */
	public function displayCont($txt, $menu = TRUE)
	{
		// Read the main template
		$page = $this->getMain();
		// Parse for menu if we need to
		if($menu)
		{
			$menutxt = $this->getMenu();
		}
		else
		{
			$menutxt = "";
		}
		$page = $this->parse("{{MENU}}", $menutxt, $page);
		// Parse for the main content
		$page = $this->parse("{{CONTENT}}", $txt, $page);
		// Parse for organization name
		$page = $this->parse("{{ORG}}", $GLOBALS['config']->org_name, $page);
		// Output the page
		echo $page;
	}
	/**
	 * displayAdminCont 
	 * Displays the admin page and allows you to specify the content
	 * @param string $txt 
	 * @access public
	 * @return void
	 */
	public function displayAdminCont($txt)
	{
		// Read the admin template
		$page = $this->readTemplate("admin");
		
		// Parse for the admin content
		$page = $this->parse("{{CONTENT}}", $txt, $page);
		// Parse for organization name
		$page = $this->parse("{{ORG}}", $GLOBALS['config']->org_name, $page);
		// Output the page
		echo $page;
	}
	/**
	 * displayAdmin 
	 * Displays the admin page using the template name given for the admin content
	 * @param string $tmpl 
	 * @access public
	 * @return void
	 */
	public function displayAdmin($tmpl)
	{
		if($this->fileExists($tmpl))
		{
			// Read the main template
			$page = $this->readTemplate("admin");

			// Parse for the main content
			$page = $this->parse("{{CONTENT}}", $this->readTemplate($tmpl), $page);
			// Parse for organization name
			$page = $this->parse("{{ORG}}", $GLOBALS['config']->org_name, $page);
			// Output the page
			echo $page;
		}
		else
		{
			die("Error: template '$tmpl.tpl' does not exist.");
		}
	}
	/**
	 * tablePager
	 * Inserts the pager HTML for the table sorter pager
	 * @access public
	 * @return void
	 */
	public function tablePager()
	{
		echo "
		<div id='pager' class='pager'>
			<form>
				<img src='images/first.png' class='first'/>
				<img src='images/prev.png' class='prev'/>
				<input type='text' class='pagedisplay'/>
				<img src='images/next.png' class='next'/>
				<img src='images/last.png' class='last'/>
				<select class='pagesize'>
					<option selected='selected'  value='10'>10</option>
					<option value='20'>20</option>
					<option value='30'>30</option>
					<option  value='40'>40</option>
				</select>
			</form>
		</div>";
	}
	/**
	 * jqPopup
	 * Inserts the HTML for a popup with the provided content
	 * @param string $title
	 * @param string $html
	 * @access public
	 * @return void
	 */
	public function jqPopup($title, $html)
	{
		echo "
			<div id='popupContact'>  
				<a id='popupContactClose' href='#'>x</a>  
				<h1 id='popupTitle'>$title</h1>  
				<p id='contactArea'>  
					$html
				</p>  
			</div>  
			<div id='backgroundPopup'></div>";
	}
}
$temp = new Template();
/**************************************/
/*    Misc Functions                  */
/**************************************/

/**
 * br2nl
 * Converts <br> to \n
 * @return void
 */
function br2nl($string){
  $return=eregi_replace('<br[[:space:]]*/?'.
    '[[:space:]]*>',chr(13).chr(10),$string);
   $return=eregi_replace('<br[[:space:]]*/?'.
    '[[:space:]]*>',chr(13),$return);
   $return=eregi_replace('<br[[:space:]]*/?'.
    '[[:space:]]*>',chr(10),$return);
  return $return;
}
/**
 * loggedInAsAdmin
 * Checks if the user is logged in and an admin
 * @return interger -1 means not logged in, 0 logged in but not admin, 1 logged in and admin
 */
function loggedInAsAdmin()
{
	if($GLOBALS['session']->isloggedin())
	{
		// The user is logged in. This is good
		// But are they an admin?
		$sql = "SELECT * FROM `worker` WHERE `username` = '".$_SESSION['user']."' AND `administrator` = 1;";
		$r = $GLOBALS['db']->query($sql);
		if(!mysql_fetch_row($r))
		{
			// They may be logged in, but they are NOT an admin
			// Show an error message on the main page with a menu
			return 0;
		}
		else
		{
			// They are an admin
			return 1;
		}
	}
	else
	{
		// Not logged in
		return -1;
	}
}
/**
 * mapChildren
 * Creatings a mapping of children and their IDs. The returned array is 0 indexed
 * @return array
 */
function mapChildren()
{
	$sql = "SELECT ID, name FROM child;";
	$db = $GLOBALS['db'];
	$r = $db->query($sql);
	$i = 0;
	while($row = mysql_fetch_row($r))
	{
		$child[ $row[0] ] = $row[1];
	}
	return $child;
}
/**
 * mapClasses
 * Creatings a mapping of classes and their IDs. The returned array is 0 indexed
 * @return array
 */
function mapClasses()
{
	$sql = "SELECT ID, name FROM class;";
	$db = $GLOBALS['db'];
	$r = $db->query($sql);
	$i = 0;
	while($row = mysql_fetch_row($r))
	{
		$class[ $row[0] ] = $row[1];
	}
	return $class;
}
/**
 * mapAdults
 * Creatings a mapping of adults and their IDs. The returned array is 0 indexed
 * @return array
 */
function mapAdults()
{
	$sql = "SELECT ID, name FROM adults;";
	$db = $GLOBALS['db'];
	$r = $db->query($sql);
	$i = 0;
	while($row = mysql_fetch_row($r))
	{
		$adults[ $row[0] ] = $row[1];
	}
	return $adults;
}
?>
